<template>
  <div>
    <div class="userBaseInfo">
      <el-avatar :size="35" :src="circleUrl"></el-avatar>
      <span class="username" v-if="comment.userEntity"
        >{{ comment.userEntity.username }}
      </span>
      <span v-if="commentParentId != 0" class="commentUser">
        回复 {{ parentName }}</span
      >
      <span class="commentTime">{{ comment.commentEntity.gmtCreated }}</span>
    </div>
    <div class="commentContent">
      <span>{{ comment.commentEntity.commentContent }}</span>
      <el-button
        size="mini"
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        v-if="comment.commentEntity.docFilesUrl"
       @click="downloadFile(comment.commentEntity.docFilesUrl,comment.commentEntity.id)"
        >下载附件</el-button
      >
      <span class="callback" @click="InputTextShow">回复</span>

      <div v-if="isChecked">
        <div class="fileUpload">
          <el-upload
            class="upload-demo"
            action="http://112.124.67.43:8088/iot/comment/fileUpload"
            :on-change="handleChange"
            :on-success="successEvent"
            :file-list="fileList"
            :limit="1"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              请上传文件,如果多个附件请上传压缩文件
            </div>
          </el-upload>
        </div>
        <el-input
          type="textarea"
          :rows="3"
          placeholder="请输入内容"
          v-model="textarea"
          style="width: 80%"
        >
        </el-input>
        <div class="commentBtnStyle">
          <el-button
            type="primary"
            size="mini"
            class="commentBtnOne"
            @click="addCommit(comment.commentEntity.id)"
            >评论</el-button
          >
          <el-button size="mini" class="commentCancel" @click="cancelComment"
            >取消</el-button
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import {
  ReqCommentById,
  ReqAddComment,
  ReqDownLoadComment,
} from "../request/index.js";
export default {
  props: {
    comment: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      circleUrl:
        "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png",
      isChecked: false,
      textarea: "",
      parentName: "",
      commentParentId: 0,
      fileList: [],
      commentFileUrl: "",
    };
  },
  methods: {
    InputTextShow() {
      this.isChecked = true;
    },
    cancelComment() {
      this.isChecked = false;
    },
    async getParentComment() {
      const parentId = this.comment.commentEntity?.parentId;
      const resultData = await ReqCommentById({ id: parentId });
      const parentName = resultData.commentVo?.userEntity?.username;
      const commentParentId = resultData.commentVo?.commentEntity?.parentId;
      this.parentName = parentName;
      this.commentParentId = commentParentId;
    },
    async addCommit(id) {
      console.log("添加评论,回复评论");
      if (this.textarea.trim().length === 0) {
        this.$message({
          type: "warning",
          message: "请输入评论的内容",
        });
      } else {
        // let formdata = new FormData();
        // formdata.append("contend", this.textarea.trim());
        // formdata.append("demandId", this.$router.history.current.query.demandId);
        // formdata.append("parentId", id);
        // formdata.append("pusherId",sessionStorage.getItem("id"));
        let formdata = {
          docFilesUrl: this.commentFileUrl,
          commentContent: this.textarea.trim(),
          demandId: this.$router.history.current.query.demandId,
          parentId: id,
          pushlisherId: sessionStorage.getItem("id"),
        };
        const resultData = await ReqAddComment(formdata);
        if (resultData.msg == "success") {
          this.$message({
            type: "success",
            message: "评论成功",
          });
          // 怎么刷新二级回复
          this.textarea = "";
          this.isChecked = false;
          this.$emit("backcall");
        }
      }
    },
    // 对文件列表操作
    handleChange(file, fileList) {
      this.fileList = fileList.slice(-3);
    },
    // 文件上传成功时
    successEvent(response, file, fileList) {
      this.commentFileUrl = response.msg;
    },
    downloadFile(url,id) {
      let arr = url.split(".")
      let typeEnd =arr[arr.length-1]
      if(typeEnd=="doc"){
        typeEnd ="application/msword"
      }
      if(typeEnd=="docx"){
        typeEnd ="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
      }
      if(typeEnd=="txt"){
        typeEnd ="application/json;charset=utf-8"
      }
      if(typeEnd=="xls"){
        typeEnd ="application/vnd.ms-excel"
      }
      if(typeEnd=="xlsx"){
        typeEnd ="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
      }
      let url_post = "http://112.124.67.43:8088/iot/comment/downloadAttachment";
      let param =new FormData;
      param.append('id',id)
      param.append("fileName","文档")     
      //post方式，param为所需要传的参数，
      // responseType: 'arraybuffer'一定要写，否则下载的文件会出现乱码
      axios
        .post(url_post, param, { responseType: "arraybuffer" })
        .then((res) => {
          let blob = new Blob([res.data], { type: typeEnd }); //type为所需要下载的文件格式，以xls文件为例
          //浏览器兼容，Google和火狐支持a标签的download，IE不支持
          if (window.navigator && window.navigator.msSaveBlob) {
            //IE浏览器、微软浏览器
            /* 经过测试，微软浏览器Microsoft Edge下载文件时必须要重命名文件才可以打开，
              IE可不重命名，以防万一，所以都写上比较好 */
            window.navigator.msSaveBlob(blob, "文件");
          } else {
            //其他浏览器
            let link = document.createElement("a"); // 创建a标签
            link.setAttribute('download', url)
            link.style.display = "none";
            let objectUrl = URL.createObjectURL(blob);
            link.href = objectUrl;
            link.click();
            URL.revokeObjectURL(objectUrl);
          }
        })
        .catch((err) => {
          this.$message.error(err.message);
        });
    },
    async created() {
      await this.getParentComment();
    },
  },
};
</script>

<style scoped>
.userBaseInfo {
  display: flex;
  align-items: center;
}
.userBaseInfo :nth-child(n) {
  margin-right: 10px;
}
.userBaseInfo .username {
  color: #f0ab00;
}
.userBaseInfo .commentUser {
  color: #aaa;
  font-size: 12px;
}
.userBaseInfo .commentTime {
  color: #aaa;
  font-size: 12px;
}
.commentContent {
  padding: 0px 50px;
  line-height: 30px;
}
.commentContent .callback {
  margin-left: 30px;
  color: #f0ab00;
  font-size: 12px;
  padding: 0px 10px;
  cursor: pointer;
}
.fileUpload {
  width: 80%;
}
.commentBtnStyle {
  width: 80%;
  position: relative;
  margin: 30px 0px;
}
.commentBtnStyle .el-button {
  position: absolute;
}
.commentBtnStyle .commentBtnOne {
  right: 80px;
}
.commentBtnStyle .commentCancel {
  right: 10px;
}
.commentItemBox {
  margin: 10px;
}
.seeMoreCallBackStyle {
  font-size: 12px;
  color: #ccc;
  cursor: pointer;
}
.download {
  color: blue !important;
}
</style>
